package com.xxl.job.executor.service.jobhandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.entity.ReturnMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wenzhuo
 * @create 2024-06-18 2024/6/18
 */
@Component
public class SettledOptionJob {
    private static Logger logger = LoggerFactory.getLogger(SettledOptionJob.class);

    @Value ("${settledOption.url}")
    private String url;

    public static final Integer successCode = 200;


    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("settledOptionJob")
    public void contractSettlementJob() throws Exception {


        try {
            //调用Core服务的updateRate接口
            // 3.创建连接与设置连接参数
            URL urlObj = new URL(url);
            //创建连接
            HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
            //设置请求为GET
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("Charset", "UTF-8");
            //发送请求
            httpConn.connect();
            //获取响应
            Integer responseCode = httpConn.getResponseCode();
            logger.info("responseCode:{}",responseCode);

            //返回200代表返回成功
            if(successCode.equals(responseCode) ){
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null){
                    response.append(line);
                }
                reader.close();

                ObjectMapper mapper = new ObjectMapper();
                try {
                    ReturnMessage returnMessage = mapper.readValue(response.toString(), ReturnMessage.class);
                    logger.info("stateCode: {}, message: {}, Data: {}",returnMessage.getState(),returnMessage.getMessage(),returnMessage.getData());

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else {
                logger.info("settled option request failed. Response Code: {}",responseCode);
            }
            //关闭连接
            httpConn.disconnect();

        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
